"ui";
// 加载jsoup.jar
// runtime.loadJar("./jar/Java-WebSocket-1.5.1.jar");
// 使用jsoup解析html
// importClass(org.java_websocket.client.WebSocketClient);
// importClass(org.java_websocket.handshake.ServerHandshake);

//console.log(threads.start(requestScreenCapture));

threads.start(function(){
    if(!requestScreenCapture()){
        toast("请求截图失败");
        exit();
    }
});





var local = storages.create("au.autojs.dog.config");

ui.layout(
    <vertical>
        <horizontal padding="2">
            <text padding="8" layout_weight="1">AutoJs小助手由易支烟开发QQ464312406</text>
            <button id="exit">退出</button>
        </horizontal>
        <horizontal padding="2">
            <input id="ipAddress" digits="1234567890.:" singleLine="true" hint="请输入IP地址" layout_weight="1" />
            <button id="connection">连接</button>
        </horizontal>
    </vertical>
);

let wss = null;

ui.exit.on("click", function (e) {
    wssClose();
    exit();
})


function initSocket(link){
    //创建一个类
    var obj={
        onOpen:function(ws,response){
            console.log('onOpen');
            ui.run(()=>ui.connection.text("断开"));
            toast("连接成功");
            
        },
        onMessage:function(ws,text){
            let info=JSON.parse(text.toString());
            console.log('onMessage',text);
            switch(info.code){
                case 202:
                    //截图
                    try{
                        let base64Img=images.toBase64(captureScreen());
                        ws.send(JSON.stringify({
                            code:202,
                            id:info.id,
                            image:base64Img
                        }));
                    }catch(e){
                        console.log(e);
                        toast("没有权限");
                    }
                    break
                case 201:
                    toast("已经有另一个连接了");
                    wssClose(false)
                    break
            }
        },
        onClosing:function(ws,code,reason){
            console.log('准备关闭')
        },
        onClosed:function(ws,code,reason){
            console.log('onClosed',code);
            wss=null;
            wssClose();
        },
        onFailure:function(ws,err,response){
            console.log('onFailure',err);
            wssClose();
        },
    }
    //实现接口WebSocketListener，用于监听事件
    listener = new WebSocketListener(obj);
    var client = new OkHttpClient();
    var request = new Request.Builder().url(link).build();
    wss=client.newWebSocket(request, listener);
    //client.dispatcher().executorService().shutdown();
}

if (local.get("link")) {
    ui.ipAddress.text(local.get("link") + "");
}

function wssClose(showToast){
    if(wss){
        wss.close(1000, null);
        ui.run(()=>ui.connection.text("连接"));
        wss = null;
        if(!showToast){
            toast("连接已断开");
        }
    }
}



ui.connection.on("click", function (e) {
    if (wss) {
        wssClose();
    } else {
        var link = new String(ui.ipAddress.getText());
        local.put("link", link.toString());
        if (!(link  && new RegExp("[\\d]+\.[\\d]+\.[\\d]+\.[\\d]+\:[\\d]").test(link))) {
            return toast("请输入正确的IP和端口");
        }
        initSocket('ws://' + link);
    }
})
